import os
import shutil

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from notifications.signals import notify

from bilimili_django import settings
from user.models import UserProfile
import time

def send_creative():
    description = "快来查看你的创作周报吧！" + "<a aria-current='page' href='/create' target='_blank'>" + "===>点击查看" + "</a>"
    sender_id = 1
    users = UserProfile.objects.all()
    for user in users:
        notify.send(sender=UserProfile.objects.get(id=1), recipient=UserProfile.objects.get(id=user.id),
                    verb='verb', customer_id=user.id, sender_id=sender_id, description=description,
                    category='SYSTEM')


def delete_temp():
    temp_path = os.path.join(settings.MEDIA_ROOT, 'videos/temp')
    current_time = time.time()
    # 遍历目录
    for dir_name in os.listdir(temp_path):
        dir_path = os.path.join(temp_path, dir_name)
        if os.path.isdir(dir_path):  # 确认为目录
            last_modified_time = os.path.getmtime(dir_path)
            time_difference = current_time - last_modified_time
            hours_difference = time_difference / 3600  # 将时间差转换为小时
            print(hours_difference)
            if hours_difference >= 1:
                shutil.rmtree(dir_path)



def start_scheduler():
    scheduler = BackgroundScheduler()
    scheduler.add_job(send_creative, trigger=CronTrigger(day_of_week='tue', hour='17', minute='00'))
    scheduler.add_job(delete_temp, 'cron', hour=4)
    scheduler.print_jobs()
    scheduler.start()
